import { request } from '@/config/api'
export interface ConvertRequest {
  inputPath: string
  outputPath: string
}

export interface FileRequest {
  filePath: string
}

export interface WriteFileRequest {
  filePath: string
  content: string
}

export interface ListFilesRequest {
  dirPath: string
  extension?: string
}

export interface LLMConfig {
  model: string
  apiKey?: string
  baseUrl?: string
  provider?: string
  temperature?: number
  maxTokens?: number
}

export interface GenerateLessonPlanRequest {
  mdContent: string
  templateContent: string
  llmConfig: LLMConfig
  prompt?: string
}

export interface ChatMessage {
  role: 'user' | 'assistant' | 'system'
  content: string
}

export interface ChatWithAIRequest {
  messages: ChatMessage[]
  llmConfig: LLMConfig
}

export interface ApiResponse<T = any> {
  success: boolean
  message: string
  data?: T
  [key: string]: any
}

export interface FileInfo {
  name: string
  path: string
  isDirectory: boolean
  size: number
  modifiedTime: string
}

class LessonPlanService {
  private static readonly BASE_URL = '/lesson-plan'

  // Doc转Md
  static async convertDocToMd(data: ConvertRequest): Promise<ApiResponse> {
    return request(`${this.BASE_URL}/convert/doc-to-md`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // PPTX转Md
  static async convertPptxToMd(data: ConvertRequest): Promise<ApiResponse> {
    return request(`${this.BASE_URL}/convert/pptx-to-md`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // Md转Doc
  static async convertMdToDoc(data: ConvertRequest): Promise<ApiResponse> {
    return request(`${this.BASE_URL}/convert/md-to-doc`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 读取文件
  static async readFile(data: FileRequest): Promise<ApiResponse<{ content: string; filePath: string }>> {
    return request(`${this.BASE_URL}/file/read`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 写入文件
  static async writeFile(data: WriteFileRequest): Promise<ApiResponse> {
    return request(`${this.BASE_URL}/file/write`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 获取文件列表
  static async listFiles(params: ListFilesRequest): Promise<ApiResponse<{ files: FileInfo[]; dirPath: string }>> {
    const queryParams = new URLSearchParams()
    queryParams.append('dirPath', params.dirPath)
    if (params.extension) {
      queryParams.append('extension', params.extension)
    }
    
    return request(`${this.BASE_URL}/files?${queryParams.toString()}`, {
      method: 'GET'
    })
  }

  // 生成教案
  static async generateLessonPlan(data: GenerateLessonPlanRequest): Promise<ApiResponse<{ content: string; llmConfig: LLMConfig }>> {
    return request(`${this.BASE_URL}/generate`, {
      method: 'POST',
      body: JSON.stringify({
        mdContent: data.mdContent,
        templateContent: data.templateContent,
        llmConfig: data.llmConfig
      })
    })
  }

  // 使用AI路由生成教案 - 避免老API问题
  static async generateLessonPlanWithAI(data: GenerateLessonPlanRequest): Promise<{ content: string }> {
    // 构建系统提示词
    const systemPrompt = `你是一个专业的教案生成助手。请根据以下内容生成教案：

参考文档内容：
${data.mdContent}

教案模板格式：
${data.templateContent}

${data.prompt ? `用户要求：
${data.prompt}` : ''}

请严格按照模板格式生成完整的教案内容。`

    const messages = [
      { role: 'system' as const, content: systemPrompt },
      { role: 'user' as const, content: '请生成教案' }
    ]

    const response = await request('/ai/chat', {
      method: 'POST',
      body: JSON.stringify({
        messages,
        model: data.llmConfig.model,
        apiKey: data.llmConfig.apiKey,
        apiUrl: data.llmConfig.baseUrl,
        temperature: data.llmConfig.temperature || 0.7,
        max_tokens: data.llmConfig.maxTokens || 4000
      })
    })

    return {
      content: response.data?.message || response.content || response.message || '生成教案失败'
    }
  }

  // 多轮对话 - 直接调用AI路由
  static async chatWithAI(data: ChatWithAIRequest): Promise<{ content: string }> {
    const response = await request('/ai/chat', {
      method: 'POST',
      body: JSON.stringify({
        messages: data.messages,
        model: data.llmConfig.model,
        apiKey: data.llmConfig.apiKey,
        apiUrl: data.llmConfig.baseUrl,
        temperature: data.llmConfig.temperature || 0.7,
        max_tokens: data.llmConfig.maxTokens || 4000
      })
    })
    
    return {
      content: response.data?.message || response.content || response.message || '抱歉，我无法生成回复。'
    }
  }

  // 检查pandoc是否可用
  static async checkPandocAvailability(): Promise<boolean> {
    try {
      // 尝试转换一个简单的测试文件来检查pandoc是否可用
      const testRequest: ConvertRequest = {
        inputPath: 'test.md',
        outputPath: 'test.docx'
      }
      
      // 这里可以调用一个专门的检查接口，或者使用现有的转换接口
      // 暂时返回true，实际项目中应该实现真正的检查逻辑
      return true
    } catch (error) {

      return false
    }
  }

  // 获取预设的LLM模型配置
  static getPresetLLMConfigs(): LLMConfig[] {
    return [
      {
        model: 'gpt-3.5-turbo',
        baseUrl: 'https://api.openai.com/v1',
        temperature: 0.7,
        maxTokens: 2000
      },
      {
        model: 'gpt-4',
        baseUrl: 'https://api.openai.com/v1',
        temperature: 0.7,
        maxTokens: 2000
      },
      {
        model: 'claude-3-sonnet',
        baseUrl: 'https://api.anthropic.com/v1',
        temperature: 0.7,
        maxTokens: 2000
      },
      {
        model: 'qwen-turbo',
        baseUrl: 'https://dashscope.aliyuncs.com/api/v1',
        temperature: 0.7,
        maxTokens: 2000
      },
      {
        model: 'glm-4',
        baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
        temperature: 0.7,
        maxTokens: 2000
      }
    ]
  }

  // 获取DOC文件列表
  static async getDocFiles(dirPath: string): Promise<FileInfo[]> {
    const response = await this.listFiles({ dirPath, extension: '.doc' })
    return response.files || []
  }

  // 获取MD文件列表
  static async getMdFiles(dirPath: string): Promise<FileInfo[]> {
    const response = await this.listFiles({ dirPath, extension: '.md' })
    return response.files || []
  }

  // 获取模板内容
  static async getTemplate(templateName: string): Promise<string> {
    const templatePath = 'd:\\WebProjects\\qdkj-course\\chapter03-05\\chapters\\Template.md'
    const response = await this.readFile({ filePath: templatePath })
    return response.content || ''
  }

  // 获取LLM模型列表
  static async getLLMModels(): Promise<LLMConfig[]> {
    return this.getPresetLLMConfigs()
  }

  // 生成输出路径
  static generateOutputPath(inputPath: string, newExtension: string): string {
    const lastDotIndex = inputPath.lastIndexOf('.')
    const basePath = lastDotIndex > 0 ? inputPath.substring(0, lastDotIndex) : inputPath
    return `${basePath}.${newExtension}`
  }

  // 验证文件路径
  static validateFilePath(filePath: string): { isValid: boolean; error?: string } {
    if (!filePath || filePath.trim() === '') {
      return { isValid: false, error: '文件路径不能为空' }
    }

    // 检查路径是否包含非法字符
    const invalidChars = /[<>:"|?*]/
    if (invalidChars.test(filePath)) {
      return { isValid: false, error: '文件路径包含非法字符' }
    }

    return { isValid: true }
  }
}

export default LessonPlanService